var pffEditorUI = {
	theSpellCheck : null,
	sourceSpellCheck : null,
	richSpellCheck : null,
	
	type : "",
	tags : "",
	dateCreated : null,
	orginalDateCreated : null,
	entryId : "",
	categories : [],
	isDraft : false,
	slug : "",
	custom_fields : [],
	
	media : [],
	
	timestampEdit : false,
	
	prefs : null,
	
	load : function () {
		var frame = document.getElementById("performancing-message");
	    
	    frame.docShell.allowAuth = false;
        frame.docShell.allowImages = true;
        frame.docShell.allowJavascript = false;
        frame.docShell.allowMetaRedirects = false;
        frame.docShell.allowPlugins = false;
        frame.docShell.allowSubframes = false;
	    
		var frame = document.getElementById("performancing-preview-display");
		
	    frame.docShell.allowAuth = false;
        frame.docShell.allowImages = true;
        frame.docShell.allowJavascript = false;
        frame.docShell.allowMetaRedirects = false;
        frame.docShell.allowPlugins = false;
        frame.docShell.allowSubframes = false;

		
			this.prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService)
			.getBranch("performancing.");
		performancingMidas.setUpMidas();
		this.setupSpellCheck();
		
		try {
			if (this.parentWindow.SCRIBEFIRE_BLOG.type.match(/wordpress|moveabletype|blogger/i)) {
				document.getElementById("cmd_splitter").setAttribute("disabled","false");
			}
		} catch (noBlogs) {
		}
		
		this.parentWindow.performancingUI.onTextBoxLoad2();
		
		var copyPaste = {
			QueryInterface: function (iid) {
				if (iid.equals(Components.interfaces.nsISupports) || iid.equals(Components.interfaces.nsIClipboardDragDropHooks))
					return this;
				else
					throw Components.results.NS_NOINTERFACE;
			},
			
			allowDrop: function (event, session) {
				return true;
			},
			
			allowStartDrag: function (event) {
				return true;
			},
			
			onCopyOrDrag: function (event, trans) {
				var data = {};
				var dataLen = {};
				trans.getTransferData("text/html", data, dataLen);
				data.value.QueryInterface(Components.interfaces.nsISupportsString);
				
				var newString = data.value.data;
				
				newString = newString.replace(/href=(['"])chrome:\/\/performancing\/content\/editor\/(blank\.html)?/g, "href=$1");
				newString = newString.replace(/href=(['"])chrome:\/\/performancing\/content\//g, "href=$1../");
				newString = newString.replace(/href=(['"])chrome:\/\/performancing\//g, "href=$1/");
				newString = newString.replace(/href=(['"])chrome:\/\//g, "href=$1//");
				
				var newData = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
				newData.data = newString;
				
				trans.setTransferData("text/html", newData, newString.length * 2);
				
				return true;
			},
			
			onPasteOrDrop: function (event, trans) {
				return true;
			}
		};
		
		try {
			var editor = document.getElementById("performancing-message");
			var params = Components.classes["@mozilla.org/embedcomp/command-params;1"]
				.createInstance(Components.interfaces.nsICommandParams);
			params.setISupportsValue("addhook", copyPaste);
			editor.commandManager.doCommand("cmd_clipboardDragDropHook", params, editor.contentWindow);
		} catch (e) {
		}
		
		// document.getElementById("cmd_font").doCommand();
	},
	
	get parentWindow() {
		var p = window.parent;
		
		if (p.wrappedJSObject) {
			return p.wrappedJSObject;
		}
		
		return p;
	},
	
	publish : function () {
		var guid = this.parentWindow.SCRIBEFIRE_BLOG.findGUID();
		
		if (!guid) {
			alert("You must select a blog before you can publish.");
		}
		else {
			var re = [];
			
			var extraOptions = this.parentWindow.SCRIBEFIRE_BLOG.extraOptions;
			
			var supportForSlugs = pffEditorUI.parentWindow.performancingEditor.supportsSlugs;
			
			window.openDialog('chrome://scribefire/content/editor/publishingOptions.xul','publishing-options','chrome,modal', re, supportForSlugs, extraOptions);
			
			if (re[0]) {
			    pffEditorUI.parentWindow.gPerformancingUtil.publish({isEdit: (re[0] == 'edit'), isPage:(re[0] == 'page'), draft:re[1], slug:re[2], custom_fields:re[3], extra_options : re[4]}); 
			}
		}
	},
	
	setupSpellCheck : function () {
		var theTextBox = null;

		//set-up the HTML source spellchecker
		var theTextElement = document.getElementById("performancing-message-source");
		var theTextBox = theTextElement.inputField.QueryInterface(Components.interfaces.nsIDOMNSEditableElement).editor;
		this.sourceSpellCheck = new sfSpellCheck();
		this.sourceSpellCheck.init(theTextBox);

		//set-up the rich text spellchecker
		theTextElement = document.getElementById("performancing-message");
		theTextBox = theTextElement.getHTMLEditor(theTextElement.contentWindow);
		this.richSpellCheck = new sfSpellCheck();
		this.richSpellCheck.init(theTextBox);

		this.theSpellcheck = this.richSpellCheck;
	},
	
	clearAll : function () {
		performancingMidas.makeBlank();
		
		document.getElementById("note-save-deck").selectedIndex = 0;
		
		pffEditorUI.parentWindow.performancingUI.clearTechnoratiTags();
		
		pffEditorUI.parentWindow.performancingEditor.setTitle("");
		pffEditorUI.parentWindow.performancingEditor.setEntryId();
		pffEditorUI.parentWindow.performancingEditor.setEntryType("note");
		pffEditorUI.parentWindow.performancingEditor.setTags("");
		pffEditorUI.parentWindow.performancingEditor.setEntryIsDraft(false);
		pffEditorUI.parentWindow.performancingEditor.setCategories();
		this.originalDateCreated = null;
	},
	
	setTabTitle : function (title) {
		if (title.length == 0) {
			title = performancingUI.getLocaleString("blankTabLabel");
		}
		else if (title.length > 19) {
			title = title.substring(0, 16) + "...";
		}
		
		pffEditorUI.parentWindow.document.getElementById("editor-tabbox").selectedTab.setAttribute("label", title);
	},
	
	addFromFlickr : function () {
		window.openDialog("chrome://scribefire/content/quickblogging/add_from_flickr.xul", "add_from_flickr", "chrome,resizable=yes,centerscreen", pffEditorUI.addFromFlickrCallback);
	},
	
	addFromFlickrCallback : function (insertCode) {
		pffEditorUI.parentWindow.performancingEditor.insertText(insertCode);
	},
	
	addFromYouTube : function () {
		window.openDialog("chrome://scribefire/content/quickblogging/add_from_youtube.xul", "add_from_youtube", "chrome,resizable=yes,centerscreen", pffEditorUI.addFromYouTubeCallback);
	},
	
	addFromYouTubeCallback : function (insertCode) {
		pffEditorUI.parentWindow.performancingEditor.insertText(insertCode);
	},
	
	getWordCount : function () {
		var count = 0;
		var words = pffEditorUI.parentWindow.performancingEditor.getContent().replace(/<[^>]+>/g, "").split(/\s/);
		
		for (var i = 0; i < words.length; i++) {
			if (words[i].length > 0) {
				count++;
			}
		}
		
		return count;
	},
	
	contextMenuShowing : function (event) {
		var menu = document.getElementById("performancing-messagemenu");
		
		if (event.target != menu) {
			return true;
		}
		
		pffEditorUI.theSpellcheck.initContextMenu(menu);
		
		var element = this.getSelectedMidasElement();
		
		if (element && (element.nodeName == "A" || element.nodeName == "IMG") && document.getElementById("performancing-editor-tabbox").selectedIndex == 0) {
			document.getElementById("cmd_editprops").setAttribute("disabled","false");
		}
		else {
			document.getElementById("cmd_editprops").setAttribute("disabled","true");
		}
	},
	
	contextMenuHiding : function (event) {
		var menu = document.getElementById("performancing-messagemenu");
		
		if (event.target != menu) {
			return true; 
		}
		
		pffEditorUI.theSpellcheck.clearContextMenu(menu);
		
	},
	
	getSelectedMidasElement : function () {
		var midas = document.getElementById("performancing-message");
		var HTMLEditor = midas.getHTMLEditor(getContentWindow(midas));
		var element = HTMLEditor.getSelectedElement("");
		
		return element;
	},
	
	editProperties : function () {
		var element = this.getSelectedMidasElement();
		
		if (element) {
			window.openDialog("chrome://scribefire/content/editor/properties.xul", "scribefire-properties", "chrome,centerscreen", element);
		}
	}
};

var performancingUI = {
	getLocaleString : function (strName, formattingValues) {
		var str = null;

        try {
            var strbundle = document.getElementById("performancingstrings");
            if (typeof formattingValues == 'undefined' || (formattingValues.length == 0)) {
                str = strbundle.getString("performancing." + strName);
            } else {
                str = strbundle.getFormattedString("performancing." + strName, formattingValues);
            }
        } catch (err) {
        }

        return str;
	}
};

function SFLOG(message) {
	var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
	consoleService.logStringMessage("SF: " + message);
}